package com.kaiwukj.android.ufamily.mvp.ui.page.service.complain;

import android.Manifest;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.di.component.DaggerServiceComponent;
import com.kaiwukj.android.ufamily.di.module.ServiceModule;
import com.kaiwukj.android.ufamily.exception.AppException;
import com.kaiwukj.android.ufamily.mvp.helper.GlideEngine;
import com.kaiwukj.android.ufamily.mvp.http.entity.params.PostComplainParams;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.ComplainResult;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.ComplainType;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.TypeAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.adapter.UploadAdapter;
import com.kaiwukj.android.ufamily.mvp.ui.page.service.ServiceContract;
import com.kaiwukj.android.ufamily.mvp.ui.widget.CustomPopupWindow;
import com.kaiwukj.android.ufamily.mvp.ui.widget.home.PopupWindowUtil;
import com.kaiwukj.android.ufamily.utils.AudioRecoderUtils;
import com.kaiwukj.android.ufamily.utils.AudioUtils;
import com.kaiwukj.android.ufamily.utils.FileUtil;
import com.kaiwukj.android.ufamily.utils.LocalMediaUtils;
import com.kaiwukj.android.ufamily.utils.VideoUtils;
import com.kaiwukj.android.ufamily.utils.upload.OnUploadListener;
import com.kaiwukj.android.ufamily.utils.upload.UploadBean;
import com.kaiwukj.android.ufamily.utils.upload.UploadUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.kaiwukj.android.ufamily.utils.Utils.runOnUiThread;

/**
 * @author Charles
 * @date 2019/8/14.
 * description：Kaiwu
 */
public class ComplainFragment extends BaseMvpFragment<ComplainPresenter> implements ServiceContract.ComplainView {
    @BindView(R.id.rv_complain_type)
    RecyclerView rvComplainType;
    @BindView(R.id.rv_complain_upload)
    RecyclerView rvComplainUpload;
    /*@BindView(R.id.ll_root_view)
    LinearLayout llRootView;*/
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.cb_anonymity)
    CheckBox cbAnonymity;
    @BindView(R.id.tv_record)
    TextView tvRecord;
    @BindView(R.id.iv_record_delete)
    ImageView ivRecodeDelete;

    private static final int REQUEST_CODE_CHOOSE_IMAGE = 1;
    private static final int REQUEST_CODE_CHOOSE_VIDEO = 2;
    private static final int MAX_LENGTH = 167772160;

    private String qiNiuToken;
    private List<String> imgs = new ArrayList<>();
    private String videoUrl;
    private String coverUrl;
    private String videoPath;
    private String audioUrl;
    private String audioPath;
    private int typeId = 0;
    private int uploadType = 0;//0:image 1 vImage 2 audio 3 video

    private UploadAdapter uploadAdapter;
    private TypeAdapter complainTypeAdapter;
    private AudioRecoderUtils audioRecoderUtils;
    private MediaPlayer mediaPlayer;
    private Timer recordTimer;

    private List<String> urls = new ArrayList<>();


    @OnClick({R.id.iv_record_delete, R.id.tv_record})
    void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.iv_record_delete:
                audioUrl = "";
                tvRecord.setVisibility(View.GONE);
                ivRecodeDelete.setVisibility(View.GONE);
                uploadAdapter.setHaveAudio(false);
                break;
            case R.id.tv_record:
                if (mediaPlayer == null) {
                    initPlayer(audioPath);
                } else {
                    if (mediaPlayer.isPlaying()) {
                        mediaPlayer.stop();
                        mediaPlayer = null;
                    } else {
                        initPlayer(audioPath);
                    }
                }
                break;
        }
    }


    public static ComplainFragment newInstance() {
        Bundle args = new Bundle();
        ComplainFragment fragment = new ComplainFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerServiceComponent.builder()
                .appComponent(appComponent)
                .serviceModule(new ServiceModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_complain;
    }

    @Override
    protected void initView() {

    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mPresenter.requestQIToken();
        initRecyclerView();
        btnCommit.setOnClickListener(view -> {
            // showLoading();
            if (!TextUtils.isEmpty(coverUrl)) {
                uploadType = 1;
                showLoading("正在上传...");
                UploadUtils.getInstance().upload(coverUrl, qiNiuToken, UploadUtils.IMAGE, onUploadListener);
            } else {
                commit();
            }
        });
        tvRecord.getBackground().setLevel(2);
        recordTimer = new Timer();
    }

    private void commit() {
        if (TextUtils.isEmpty(etContent.getText().toString())) {
            showMessage("请填写投诉详情");
            return;
        }
        if (typeId == 0) {
            showMessage("请选择投诉类型");
            return;
        }
        PostComplainParams complainRequest = new PostComplainParams();
        complainRequest.setAnonymous(cbAnonymity.isChecked() ? 1 : 0);
        complainRequest.setContent(etContent.getText().toString());
        StringBuilder stringBuffer = new StringBuilder();
        if (imgs.size() > 0) {
            String imglists;
            for (int i = 0; i < imgs.size(); i++) {
                stringBuffer.append(imgs.get(i).trim()).append(",");
            }
            imglists = stringBuffer.substring(0, stringBuffer.length() - 1);
            complainRequest.setImg(imglists);
        }
        complainRequest.setVideo(videoUrl);
        complainRequest.setVoice(audioUrl);
        complainRequest.setCoverUrl(coverUrl);
        complainRequest.setType(typeId);
        complainRequest.setCommunityId(getApp().getCommunityId());
        showLoading("正在提交");
        mPresenter.postComplain(complainRequest);
    }

    private void initRecyclerView() {
//        配置投诉类型列表
        List<ComplainType> data = new ArrayList<>();
        data.add(new ComplainType(1, "清洁卫生"));
        data.add(new ComplainType(2, "保安"));
        data.add(new ComplainType(3, "电梯"));
        data.add(new ComplainType(4, "设施设备"));
        data.add(new ComplainType(5, "绿化"));
        data.add(new ComplainType(6, "房屋质量"));
        data.add(new ComplainType(7, "物业管理人员"));
        //data.add(new ComplainType(8, "电梯"));
        data.add(new ComplainType(8, "其他"));
        complainTypeAdapter = new TypeAdapter(getContext(), R.layout.item_type, data);
        rvComplainType.setLayoutManager(new GridLayoutManager(getContext(), 3));
        rvComplainType.setAdapter(complainTypeAdapter);
        complainTypeAdapter.setOnSelectedListener(id -> typeId = id);
        complainTypeAdapter.check(0);

//        配置上传rv
        uploadAdapter = new UploadAdapter(getContext());
        uploadAdapter.setMaxImgs(3);
        rvComplainUpload.setLayoutManager(new GridLayoutManager(getContext(), 4));
        rvComplainUpload.setAdapter(uploadAdapter);
        uploadAdapter.setOnItemClickListener(new UploadAdapter.onItemClickListener() {
            @Override
            public void onAudioClick() {
                requestAudioPermissions();
            }

            @Override
            public void onVideoClick() {
                requestPermissions(2);
            }

            @Override
            public void onShowVideoClick(String coverUrl) {
                PopupWindowUtil.createVideoPop(getActivity(), videoPath, coverUrl).showCenter(R.layout.fragment_complain);
            }

            @Override
            public void onDeleteVideoClick() {
                uploadAdapter.setVideoUrl("");
                videoUrl = "";
                coverUrl = "";
            }

            @Override
            public void onAddClick() {
                requestPermissions(1);
            }

            @Override
            public void onDelImgClick(int position) {
                uploadAdapter.removeImg(position);
                imgs.remove(position);
            }

            @Override
            public void onImgClick(List<String> imgUrls, int position) {
                PopupWindowUtil.createImageDialog(getActivity(), imgUrls.get(position)).showCenter(R.layout.fragment_complain);
            }
        });
    }

    @SuppressLint("CheckResult")
    void requestPermissions(int type) {
        RxPermissions rxPermission = new RxPermissions(getActivity());
        Disposable disposable = rxPermission
                .requestEach(
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                )
                .subscribe(permission -> {
                    if (permission.granted) {
                        // 用户已经同意该权限
                        switch (type) {
                            case 1:
                                PictureSelector.create(this)
                                        .openGallery(PictureMimeType.ofImage())
                                        .isCompress(true)
                                        .maxSelectNum(3 - imgs.size())
                                        .imageEngine(GlideEngine.createGlideEngine())
                                        .theme(R.style.MyImagePickerStyle)
                                        //.forResult(PictureConfig.CHOOSE_REQUEST);
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(List<LocalMedia> result) {
                                                List<String> paths = new ArrayList<>();
                                                for (LocalMedia media : result) {
                                                    if (media.isCompressed()) {
                                                        paths.add(media.getCompressPath());
                                                    } else {
                                                        paths.add(media.getPath());
                                                    }
                                                }

                                                uploadImage(paths);
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                                break;
                            case 2:
                                PictureSelector.create(this)
                                        .openGallery(PictureMimeType.ofVideo())
                                        .maxVideoSelectNum(1)
                                        .videoMaxSecond(15)
                                        .queryMaxFileSize(50)
                                        .isPreviewVideo(true)
                                        .maxSelectNum(1)
                                        .imageEngine(GlideEngine.createGlideEngine())
                                        .theme(R.style.MyImagePickerStyle)
                                        .forResult(new OnResultCallbackListener<LocalMedia>() {
                                            @Override
                                            public void onResult(List<LocalMedia> result) {
                                                //videoPath = result.get(0).getPath();
                                                LocalMediaUtils.handlePath(result);
                                                subscribe(Observable.create((ObservableOnSubscribe<String>) emitter -> {
                                                    VideoUtils.getInstance().startCompressed(getContext(), result.get(0).getRealPath(), -1, new VideoUtils.OnVideoDealListener() {
                                                        @Override
                                                        public void onSuccess(String filePath) {
                                                            emitter.onNext(filePath);
                                                        }

                                                        @Override
                                                        public void onFailed(int errorCode, String errorMsg) {
                                                            // showMessage(errorCode + ":" + errorMsg);
                                                            emitter.onError(new AppException(errorCode, errorMsg));
                                                        }

                                                        @Override
                                                        public void onProgressUpdate(float progress) {
                                                        }
                                                    });
                                                })
                                                        .doOnSubscribe(act -> showLoading("正在处理..."))
                                                        .doFinally(() -> hideLoading())
                                                        .subscribeOn(Schedulers.computation())
                                                        .observeOn(AndroidSchedulers.mainThread())
                                                        .subscribe(result1 -> {
                                                            uploadVideo(result1);
                                                        }, error -> {
                                                            if (error instanceof AppException) {
                                                                if (((AppException) error).getErrCode() == 8 || ((AppException) error).getErrCode() == 9) {
                                                                    uploadVideo(result.get(0).getRealPath());
                                                                    return;
                                                                }
                                                            }
                                                            showMessage(Objects.requireNonNull(error.getMessage()));
                                                        }));
                                            }

                                            @Override
                                            public void onCancel() {

                                            }
                                        });
                                break;
                        }
                    } else if (permission.shouldShowRequestPermissionRationale) {
                        // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框

                    } else {
                        // 用户拒绝了该权限，并且选中『不再询问』

                    }
                });

        subscribe(disposable);
    }

    private OnUploadListener onUploadListener = new OnUploadListener() {
        @Override
        public void onUploadImage(UploadBean result) {
            if (uploadType == 1) {
                coverUrl = result.getNormalUrl();
                commit();
            } else if (uploadType == 2) {
                tvRecord.setVisibility(View.VISIBLE);
                ivRecodeDelete.setVisibility(View.VISIBLE);
                audioUrl = result.getNormalUrl();
            } else if (uploadType == 3) {
                videoUrl = result.getNormalUrl();

            }
            hideLoading();
        }

        @Override
        public void onUploadImages(List<UploadBean> results) {
            for (UploadBean bean : results) {
                imgs.add(bean.getNormalUrl());
            }
            hideLoading();
        }

        @Override
        public void onError(int errCode, String errMsg) {
            LogUtils.e("errCode:" + errCode + "\nerrMsg:" + errMsg);
            hideLoading();
        }
    };

    private void uploadImage(List<String> filePaths) {
        uploadType = 0;
        urls = filePaths;
        uploadAdapter.addData(urls);
        UploadUtils.getInstance().uploadImages(urls, qiNiuToken, onUploadListener);
        showLoading("正在处理...");
    }

    private void uploadVideo(String filePath) {
        videoPath = filePath;
        // 视频大小
        long videoSize = 0;
        try {
            videoSize = FileUtil.getFileSize(new File(filePath));
        } catch (Exception e) {
            e.printStackTrace();
        }
//            showLog("videoPath== " + videoPath + " videoSize== " + videoSize);
        //转换文件大小类型
        if (videoSize > MAX_LENGTH) {
            showMessage("大小超出限制，最大20MB");
            return;
        }
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(new File(filePath).getAbsolutePath());
        // 通过视频路径获取bitmap
        Bitmap bitmap = mmr.getFrameAtTime();
        //把bitmap保存到sdcard然后得到图片的路径
        String imagePath = FileUtil.saveBitmapToSDCard(bitmap, System.currentTimeMillis() + ".jpg");
        //显示到控件上
        coverUrl = imagePath;
        uploadAdapter.setVideoUrl(imagePath);
        uploadType = 3;
        UploadUtils.getInstance().upload(filePath, qiNiuToken, UploadUtils.VIDEO, onUploadListener);
        showLoading("正在处理...");
    }

    @SuppressLint("CheckResult")
    void requestAudioPermissions() {
        RxPermissions rxPermission = new RxPermissions(getActivity());
        subscribe(rxPermission.requestEach(Manifest.permission.RECORD_AUDIO).subscribe(permission -> {
            if (permission.granted) {
                // 用户已经同意该权限
                audioRecoderUtils = new AudioRecoderUtils();
                audioRecoderUtils.setOnAudioStatusUpdateListener(new AudioRecoderUtils.OnAudioStatusUpdateListener() {
                    @Override
                    public void onUpdate(double db, long time) {
                        LogUtils.i("录音中");
                    }

                    @Override
                    public void onStop(String filePath) {
                        audioPath = filePath;
                        try {
                            tvRecord.setText(AudioUtils.getAmrDuration(new File(filePath)) + "\"");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        uploadAdapter.setHaveAudio(true);
                        uploadType = 2;
                        UploadUtils.getInstance().upload(audioRecoderUtils.getFilePath(), qiNiuToken,
                                UploadUtils.AUDIO, onUploadListener);
                        showLoading();
                        LogUtils.i("录音结束");
                    }
                });
                LogUtils.i("开始录音");
                audioRecoderUtils.startRecord();
                showRecordPop();
            } else if (permission.shouldShowRequestPermissionRationale) {
                // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
            } else {
                // 用户拒绝了该权限，并且选中『不再询问』
            }
        }));
    }

    private void showRecordPop() {
        CustomPopupWindow customPopupWindow = new CustomPopupWindow.Builder(getActivity())
                .setAnimationStyle(R.anim.pop_enter_anim)
                .setFouse(true)
                .setOutSideCancel(false)
                .setwidth(ViewGroup.LayoutParams.MATCH_PARENT)
                .setheight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setContentView(R.layout.pop_audio_record)
                .builder();
        ViewGroup rlRoot = (ViewGroup) customPopupWindow.getItemView(R.id.rl_root);
        rlRoot.setOnClickListener(view -> {
            if (audioRecoderUtils != null) {
                audioRecoderUtils.stopRecord();
                customPopupWindow.dismiss();
            }
        });
        customPopupWindow.showCenter(R.layout.fragment_complain);
    }

    private void initRecordTimer() {
        recordTimer = new Timer();
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(() -> {
                    if (tvRecord != null) {
                        tvRecord.getBackground().setLevel(tvRecord.getBackground().getLevel() == 2 ? 1 : 2);
                    }
                });
            }
        };
        recordTimer.schedule(timerTask, 0, 500);
    }

    private void initPlayer(String filePath) {
        initRecordTimer();
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setOnCompletionListener(mediaPlayer -> {
                if (recordTimer != null) {
                    recordTimer.cancel();
                }
            });
            try {
                mediaPlayer.setDataSource(filePath);
                if (!mediaPlayer.isPlaying()) {
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                }
            } catch (IOException e) {
                mediaPlayer = null;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {
        if (recordTimer != null) {
            recordTimer.cancel();
        }
        super.onDestroyView();
    }

    @Override
    public void onFetchComplainList(List<ComplainResult> results) {

    }

    @Override
    public void onGetQiNiuToken(String token) {
        qiNiuToken = token;
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == ComplainPresenter.COMMIT) {
            uploadType = 0;
            showMessage("提交成功");
            new Handler().postDelayed(this::killMyself, 800);
        }
    }

}
